﻿using HealthcareSystem.API.Read.Application.Command.Team;
using HealthcareSystem.API.Read.DTO.Team;
using HealthcareSystem.Domain.BasicSettings.Team;
using MediatR;
using System.Collections.Generic;
using WeekExam.PassPort.ErrorCode;
using WeekExam.PassPort.Infrastructure.Interface;

namespace HealthcareSystem.API.Read.Application.CommandHandel.Team
{
    /// <summary>
    /// 机构查询请求
    /// </summary>
    public class QueryInstitutionCommandHandler : IRequestHandler<QueryInstitutionCommand, ApiResult<ApiPaging<List<Institution>>>>
    {
        private readonly IBaseRepository<Institution> instRep;

        public QueryInstitutionCommandHandler(IBaseRepository<Institution> instRep)
        {
            this.instRep = instRep;
        }

        public Task<ApiResult<ApiPaging<List<Institution>>>> Handle(QueryInstitutionCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<List<Institution>>> result=new ApiResult<ApiPaging<List<Institution>>>();
            result.Code=ResultCode.查询成功;
            result.Message=ResultCode.查询成功.ToString();

            var res = instRep.GetAll().Where(x=>!x.IsDelete);

            if (!string.IsNullOrEmpty(request.InstitutionName))
            {
                res = res.Where(x => x.InstitutionName.Contains(request.InstitutionName));
            }

            

            //总条数
            var totalcount=res.Count();
            //总页数   
            var totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.pagesize);
            //排序
            res = res.OrderByDescending(x => x.InstitutionId).Skip((request.pagindex - 1) * request.pagesize).Take(request.pagesize);
            ApiPaging<List<Institution>> paging = new ApiPaging<List<Institution>>();
            paging.totalCount = totalcount;
            paging.totalPage = totalpage;
            paging.Data = res.ToList();
            result.Data = paging;
            return Task.FromResult(result);

        }

    }
}
